package com.emode.util;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class FileUtil
{
  public static final int BUFFER_SIZE = 4096;
  public static String getWebRootPath(){
		return ServletActionContext.getServletContext().getRealPath("/");
	}
  /**
	 * 文件复制 文件复制到哪里？---> path/upload/20140411/182333.gif
		生成不重复的日期文件夹，改文件名
	 * @param myfile
	 * @param fileName
	 * @throws IOException
	 */
	public static String fileCopy(File myfile,String fileName,String photopath) throws IOException{
		String path=ServletActionContext.getServletContext().getRealPath("/");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		String dirpath=photopath+sdf.format(new Date());
		String houzui=fileName.substring(fileName.lastIndexOf("."), fileName.length());
		sdf=new SimpleDateFormat("HHmmssSSS");
		String filename=sdf.format(new Date())+houzui;
		//如果文件夹不存在，就创建文件夹
		File dir=new File(path+dirpath);
		//File dir=new File(exPath+dirpath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		InputStream in=new FileInputStream(myfile);
		OutputStream out=new FileOutputStream(new File(dir,filename));
		int len=0;
		byte[] b=new byte[1024];
		while((len=in.read(b))!=-1){
			out.write(b,0,len);
		}
		out.flush();
		out.close();
		in.close();
		return dirpath+"\\"+filename;
	}
	

  public static int copy(File in, File out)
    throws IOException
  {
    return copy(new BufferedInputStream(new FileInputStream(in)), new BufferedOutputStream(new FileOutputStream(out)));
  }

  public static void copy(byte[] in, File out)
    throws IOException
  {
    ByteArrayInputStream inStream = new ByteArrayInputStream(in);
    OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
    copy(inStream, outStream);
  }

  public static byte[] copyToByteArray(File in)
    throws IOException
  {
    return copyToByteArray(new BufferedInputStream(new FileInputStream(in)));
  }

  public static int copy(InputStream in, OutputStream out)
    throws IOException
  {
    try
    {
      int byteCount = 0;
      byte[] buffer = new byte[4096];
      int bytesRead = -1;
      while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
        byteCount += bytesRead;
      }
      out.flush();
      int i = byteCount;

      return i;
    }
    finally
    {
      try
      {
        in.close();
      } catch (IOException ex) {
      }
      try {
        out.close();
      }
      catch (IOException ex)
      {
      }
    }
  }

  public static void copy(byte[] in, OutputStream out)
    throws IOException
  {
    try
    {
      out.write(in);
      try
      {
        out.close(); } catch (IOException ex) { } } finally { try { out.close();
      }
      catch (IOException ex)
      {
      }
    }
  }

  public static byte[] copyToByteArray(InputStream in)
    throws IOException
  {
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
    copy(in, out);
    return out.toByteArray();
  }

  public static int copy(Reader in, Writer out)
    throws IOException
  {
    try
    {
      int byteCount = 0;
      char[] buffer = new char[4096];
      int bytesRead = -1;
      while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
        byteCount += bytesRead;
      }
      out.flush();
      int i = byteCount;

      return i;
    }
    finally
    {
      try
      {
        in.close();
      } catch (IOException ex) {
      }
      try {
        out.close();
      }
      catch (IOException ex)
      {
      }
    }
  }

  public static void copy(String in, Writer out)
    throws IOException
  {
    try
    {
      out.write(in);
      try
      {
        out.close(); } catch (IOException ex) { } } finally { try { out.close();
      }
      catch (IOException ex)
      {
      }
    }
  }

  public static String copyToString(Reader in)
    throws IOException
  {
    StringWriter out = new StringWriter();
    copy(in, out);
    return out.toString();
  }

  public static List<String> readLines(Reader input) throws IOException {
    BufferedReader reader = new BufferedReader(input);
    List list = CollectionUtil.newArrayList();
    String line = reader.readLine();
    while (line != null) {
      list.add(line);
      line = reader.readLine();
    }
    return list;
  }

  public static String readFile(File file) throws IOException {
    Reader in = new FileReader(file);
    StringWriter out = new StringWriter();
    copy(in, out);
    return out.toString();
  }

  public static String readFile(File file, String encoding) throws IOException {
    InputStream inputStream = new FileInputStream(file);
    return toString(encoding, inputStream);
  }

  public static String toString(InputStream inputStream) throws UnsupportedEncodingException, IOException {
    Reader reader = new InputStreamReader(inputStream);
    StringWriter writer = new StringWriter();
    copy(reader, writer);
    return writer.toString();
  }

  public static String toString(String encoding, InputStream inputStream) throws UnsupportedEncodingException, IOException {
    Reader reader = new InputStreamReader(inputStream, encoding);
    StringWriter writer = new StringWriter();
    copy(reader, writer);
    return writer.toString();
  }

  public static void saveFile(File file, String content) {
    saveFile(file, content, null, false);
  }

  public static void saveFile(File file, String content, boolean append) {
    saveFile(file, content, null, append);
  }

  public static void saveFile(File file, String content, String encoding) {
    saveFile(file, content, encoding, false);
  }

  public static void saveFile(File file, String content, String encoding, boolean append) {
    try {
      FileOutputStream output = new FileOutputStream(file, append);
      Writer writer = new OutputStreamWriter(output, encoding);
      writer.write(content);
      writer.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static String getRelativePath(File baseDir, File file)
  {
    if (baseDir.equals(file)) {
      return "";
    }
    if (baseDir.getParentFile() == null) {
      return file.getAbsolutePath().substring(baseDir.getAbsolutePath().length());
    }
    return file.getAbsolutePath().substring(baseDir.getAbsolutePath().length() + 1);
  }

  public static InputStream getInputStream(String file) throws FileNotFoundException {
    InputStream inputStream = null;
    if (file.startsWith("classpath:"))
      inputStream = FileUtil.class.getClassLoader().getResourceAsStream(file.substring("classpath:".length()));
    else {
      inputStream = new FileInputStream(file);
    }
    return inputStream;
  }

  public static File mkdir(String dir, String file) {
    if (dir == null) throw new IllegalArgumentException("dir must be not null");
    File result = new File(dir, file);
    parnetMkdir(result);
    return result;
  }

  public static void parnetMkdir(File outputFile) {
    if (outputFile.getParentFile() != null)
      outputFile.getParentFile().mkdirs();
  }

  public static File getFileByClassLoader(String resourceName) throws IOException
  {
    Enumeration urls = FileUtil.class.getClassLoader().getResources(resourceName);
    if (urls.hasMoreElements()) {
      return new File(((URL)urls.nextElement()).getFile());
    }
    throw new FileNotFoundException(resourceName);
  }

  public static String getExtension(String filename)
  {
    if (filename == null) {
      return null;
    }
    int index = filename.lastIndexOf(".");
    if (index == -1) {
      return "";
    }
    return filename.substring(index);
  }

  public static void deleteDirectory(File directory)
    throws IOException
  {
    if (!(directory.exists())) {
      return;
    }

    cleanDirectory(directory);
    if (!(directory.delete())) {
      String message = "Unable to delete directory " + directory + ".";
      throw new IOException(message);
    }
  }

  public static boolean deleteQuietly(File file)
  {
    if (file == null)
      return false;
    try
    {
      if (file.isDirectory())
        cleanDirectory(file);
    }
    catch (Exception e)
    {
    }
    try {
      return file.delete(); } catch (Exception e) {
    }
    return false;
  }

  public static void cleanDirectory(File directory)
    throws IOException
  {
    String message;
    if (!(directory.exists())) {
      message = directory + " does not exist";
      throw new IllegalArgumentException(message);
    }

    if (!(directory.isDirectory())) {
      message = directory + " is not a directory";
      throw new IllegalArgumentException(message);
    }

    File[] files = directory.listFiles();
    if (files == null) {
      throw new IOException("Failed to list contents of " + directory);
    }

    IOException exception = null;
    for (int i = 0; i < files.length; ++i) {
      File file = files[i];
      try {
        forceDelete(file);
      } catch (IOException ioe) {
        exception = ioe;
      }
    }

    if (null != exception)
      throw exception;
  }

  public static void forceDelete(File file) throws IOException
  {
    if (file.isDirectory()) {
      deleteDirectory(file);
    } else {
      boolean filePresent = file.exists();
      if (!(file.delete())) {
        if (!(filePresent)) {
          throw new FileNotFoundException("File does not exist: " + file);
        }
        String message = "Unable to delete file: " + file;
        throw new IOException(message);
      }
    }
  }

  public static boolean exists(String filePath)
  {
    return new File(filePath).exists();
  }

  public static boolean isFile(String filePath) {
	  System.out.println(filePath);
    return ((new File(filePath).exists()) && (new File(filePath).isFile()));
  }

  public static boolean isDir(String filePath) {
    return ((new File(filePath).exists()) && (new File(filePath).isDirectory()));
  }

  public static String getSuffix(String fileName)
  {
    return fileName.substring(fileName.lastIndexOf(".") + 1);
  }

  public static String getFileName(String filePath)
  {
    return filePath.substring(filePath.lastIndexOf("/") + 1);
  }

  public static String getNoSuffixFilePath(String filePath)
  {
    return filePath.substring(0, filePath.lastIndexOf("."));
  }
}